# apps/matrix_fo/matrix_fo/overrides/purchase_order.py
import json
import frappe
from frappe.utils import flt
from frappe.model.mapper import get_mapped_doc

@frappe.whitelist()
def make_purchase_receipt(source_name, target_doc=None, args=None):
    """兼容 Frappe map_docs 第三个参数 args（含 filtered_children）"""
    if isinstance(args, str):
        try:
            args = frappe.parse_json(args)
        except Exception:
            args = {}
    args = args or {}
    filtered = set(args.get("filtered_children") or [])

    def set_missing_values(source, target):
        target.ignore_pricing_rule = 1
        target.run_method("set_missing_values")
        target.run_method("calculate_taxes_and_totals")

    def update_item(obj, target, source_parent):
        pending = flt(obj.qty) - flt(obj.received_qty)
        target.qty = pending
        target.stock_qty = pending * flt(obj.conversion_factor)
        target.amount = pending * flt(obj.rate)
        target.base_amount = target.amount * flt(source_parent.conversion_rate)

    def condition(d):
        # 原条件：还有未收货且不是“供应商送货”行
        pending_ok = abs(d.received_qty) < abs(d.qty) and d.delivered_by_supplier != 1
        # 新增：如果前端勾选了子行，只保留勾选的 childname
        child_ok = (d.name in filtered) if filtered else True
        return pending_ok and child_ok

    return get_mapped_doc(
        "Purchase Order",
        source_name,
        {
            "Purchase Order": {
                "doctype": "Purchase Receipt",
                "field_map": {"per_billed": "per_billed"},
                "validation": {"docstatus": ["=", 1]},
            },
            "Purchase Order Item": {
                "doctype": "Purchase Receipt Item",
                "field_map": {"name": "purchase_order_item", "parent": "purchase_order", "bom": "bom"},
                "postprocess": update_item,
                "condition": condition,
            },
            "Purchase Taxes and Charges": {
                "doctype": "Purchase Taxes and Charges",
                "add_if_empty": True,
            },
        },
        target_doc,
        set_missing_values,
    )
